//
//  FirstScrollView.m
//  PetAPP
//
//  Created by apple on 16/2/27.
//  Copyright © 2016年 Yuming. All rights reserved.
//

#import "FirstScrollView.h"

#define GUIDE_COUNT 3
#define SCREEN_FRAME ([UIScreen mainScreen].bounds)
#define SCREEN_WIDTH ([UIScreen mainScreen].bounds.size.width)
#define SCREEN_HEIGHT ([UIScreen mainScreen].bounds.size.height)

@interface FirstScrollView ()

@property (nonatomic, assign) NSInteger number;

@end

@implementation FirstScrollView

- (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:SCREEN_FRAME];
    if (self) {
        
        self.number = 1;
        self.bounces = NO;
        self.contentSize = CGSizeMake(SCREEN_WIDTH * GUIDE_COUNT, SCREEN_HEIGHT);
        self.backgroundColor = [UIColor blackColor];
        self.showsHorizontalScrollIndicator = NO;
        self.pagingEnabled = YES;
        self.backgroundColor = [UIColor clearColor];
        self.delegate = self;
        for (int i = 0; i< GUIDE_COUNT; i++) {
            
            UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(SCREEN_WIDTH * i, 0, SCREEN_WIDTH ,SCREEN_HEIGHT)];
            [imageView setBackgroundColor:[UIColor redColor]];
            [imageView setImage:[UIImage imageNamed:[NSString stringWithFormat:@"boot%d",i + 1]]];
            [self addSubview:imageView];
            
            /** 在最后一页的图片上添加点击进入的按钮 */
            if (i == GUIDE_COUNT - 1) {
                UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
                button.frame = CGRectMake(100, 620, 220, 60);
                [button addTarget:self action:@selector(beginClick) forControlEvents:UIControlEventTouchUpInside];
                imageView.userInteractionEnabled = YES;
                [imageView addSubview:button];
            }
            /** 实现点击能更改图片 */
            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTapAction:)];
            imageView.userInteractionEnabled = YES;
            [imageView addGestureRecognizer:tap];
            
        }
    }
    return self;
}
#pragma mark - 点击事件
- (void)beginClick {
    /** 关闭scroll的用户交互 */
    self.userInteractionEnabled = NO;
    [UIView animateWithDuration:0.3 animations:^{
        self.alpha = 0;
    } completion:^(BOOL finished) {
        /** 进入VC后将scroll销毁 */
        [self removeFromSuperview];
    }];
}

-(void)handleTapAction:(UITapGestureRecognizer *)tap {
    /** 判断用户是在第几张图片以免越界 */
    if (self.number < GUIDE_COUNT) {
        CGPoint scrollPoint = CGPointMake(SCREEN_WIDTH * self.number, 0);
        [self setContentOffset:scrollPoint animated:YES];
        self.number++;
    }
}

#pragma mark - 设置
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    /** 滑动引导页的时候更改number的值以确保下次点击图片的时候能实现滑动 */
    self.number = (int)(scrollView.contentOffset.x / SCREEN_WIDTH) + 1;
}

@end
